# python rabbitmq 消化者
# exchange:autotest
# routing_key:api_disconnect_device
# queue:api_disconnect_device_queue

import pika
import json
from library.trpc import Trpc
import logging.config
import time

autotest_trpc = Trpc('autotest')
device_trpc = Trpc('tcdevices')

config = {
    'exchange': 'autotest',
    'routing_key': 'api_disconnect_device',
    'queue': 'api_disconnect_device_queue',
}

dictConfig = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'master_format': {
            'class': 'logging.Formatter',
            'format': '%(asctime)s [%(name)s] [%(levelname)s] %(filename)s - %(message)s',
            'datefmt': '%Y-%m-%d %H:%M:%S'
        }
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'level': logging.DEBUG,
            'formatter': 'master_format',
        },
        'disconnnectFileHandler': {
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': './logs/mq/disconnect.log',
            'level': logging.INFO,
            'formatter': 'master_format',
            'interval': 1,
            'when': 'D'
        },
    },
    'loggers': {
        'disconnectLogger': {
            'handlers': ['console', 'disconnnectFileHandler'],
            'level': 'INFO'
        }
    }
}

logging.config.dictConfig(dictConfig)
log = logging.getLogger(name='disconnectLogger')

credentials = pika.PlainCredentials('autotest', '123456')
connection = pika.BlockingConnection(pika.ConnectionParameters(
            host = '127.0.0.1', port = '5672', virtual_host = 'autotest', credentials = credentials))
channel = connection.channel()
channel.exchange_declare(config['exchange'], 'direct')
channel.queue_declare(queue = config['queue'], durable = False)
channel.queue_bind(exchange = config['exchange'], queue = config['queue'], routing_key = config['routing_key'])


def push_rabbitmq(exchange, routing_key, queue, data):
    credentials = pika.PlainCredentials('autotest', '123456')
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='127.0.0.1', port='5672', virtual_host='autotest', credentials=credentials))
    channel = connection.channel()
    channel.exchange_declare(exchange, 'direct')
    channel.queue_declare(queue=queue)
    channel.queue_bind(exchange=exchange, queue=queue, routing_key=routing_key)
    channel.basic_publish(exchange=exchange, routing_key=routing_key, body=data)
    connection.close()

def callback(ch, method, properties, body):
    data = json.loads(body.decode())
    serial = data['serial']
    time_out_id = data['time_out_id']
    ttl = data['ttl']
    end_time = int(time.time())

    if ttl < end_time:
        # 查询数据判断是否需要释放设备
        res = autotest_trpc.requests('get', '/monkey/time_out/{}'.format(time_out_id))

        if len(res) != 0:
            timeoutData = res[0]
            if timeoutData['release'] == 0:
                autotest_trpc.requests('post', '/monkey/device/release', body={"serial": serial})
                device_trpc.requests('post', '/tcdevices/disconnect', body={"serial": serial})
                log.info('[设备超时断开] {}'.format(data))
    else:
        # 重新返回队列
        push_rabbitmq(exchange='autotest', routing_key='api_disconnect_device', queue="api_disconnect_device_queue", data=json.dumps(data))
        log.info('我tm重新回到队列了!')
        time.sleep(3)

    ch.basic_ack(delivery_tag=method.delivery_tag)


channel.basic_consume(config['queue'], callback, False)

channel.start_consuming()